<template>
  <div>
    <!-- 基本信息-->
    <h1 class="basic_info">基本信息</h1>
    <div class="clear"></div>

    <!-- 基本信息表 -->
    <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm"
    >
      <el-form-item label="模板名称" prop="name">
        <el-input
            v-model="ruleForm.name"
            placeholder="请输入模板名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="模板描述" prop="description">
        <el-input
            type="textarea"
            v-model="ruleForm.description"
            placeholder="请输入模板描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="适用人群" prop="applicantGroupId">
        <el-select
            v-model="ruleForm.applicantGroupId"
            placeholder="选择适用人群"
        >
          <el-option
              v-for="item in applicantGroupOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 申请表字段 -->
    <div class="material-header">
      <h1 class="material_category">申请表字段</h1>
      <el-button
          class="addField"
          round
          @click="addApplicationField"
          style="height: auto"
      >
        + 添加字段
      </el-button>
    </div>

    <div class="clear"></div>
    
    <!--申请表字段表-->
    <el-table
        :data="applicationFieldData"
        border
        style="width: 100%"
        class="material_category_table"
        ref="applicationTable"
    >
      <el-table-column prop="category" label="材料类目"></el-table-column>
      <el-table-column prop="fieldName" label="字段名称"></el-table-column>
      <el-table-column prop="fieldLabel" label="字段标签"></el-table-column>
      <el-table-column prop="fieldType" label="字段类型"></el-table-column>
      <el-table-column prop="required" label="是否必填">
        <template slot-scope="scope">
          <span>{{ scope.row.required ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序号"></el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="200"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEditField(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteField(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 材料清单 -->
    <div class="material-header">
      <h1 class="material_category">材料清单</h1>
      <el-button
          class="addField"
          round
          @click="addField"
          style="height: auto"
      >
        + 添加字段
      </el-button>
    </div>

    <div class="clear"></div>
    
    <!--材料清单表-->
    <el-table
        :data="materialCategoryData"
        border
        style="width: 100%"
        class="material_category_table"
        ref="materialTable"
    >
      <el-table-column prop="category" label="材料类目"></el-table-column>
      <el-table-column prop="fieldName" label="字段名称"></el-table-column>
      <el-table-column prop="fieldLabel" label="字段标签"></el-table-column>
      <el-table-column prop="fieldType" label="字段类型"></el-table-column>
      <el-table-column prop="required" label="是否必填">
        <template slot-scope="scope">
          <span>{{ scope.row.required ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sortOrder" label="排序号"></el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="200"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEditMaterial(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDeleteMaterial(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="primary" size="medium" @click="handleConfirm">确认</el-button>
      <el-button size="medium" @click="$router.go(-1)">取消</el-button>
    </div>

    <!-- 添加字段弹窗 -->
    <el-dialog title="添加字段" :visible.sync="dialogVisible" width="50%">
      <el-form :model="fieldForm" :rules="fieldRules" ref="fieldForm" label-width="100px">
        <el-form-item label="材料类目" prop="category">
          <el-input v-model="fieldForm.category" placeholder="请输入材料类目"></el-input>
        </el-form-item>
        <el-form-item label="字段名称" prop="fieldName">
          <el-input v-model="fieldForm.fieldName" placeholder="请输入字段名称"></el-input>
        </el-form-item>
        <el-form-item label="字段标签" prop="fieldLabel">
          <el-input v-model="fieldForm.fieldLabel" placeholder="请输入字段标签"></el-input>
        </el-form-item>
        <el-form-item label="字段类型" prop="fieldType">
          <el-select v-model="fieldForm.fieldType" placeholder="请选择字段类型" @change="handleFieldTypeChange">
            <el-option label="文本框" value="text"></el-option>
            <el-option label="图片" value="image"></el-option>
            <el-option label="日期" value="date"></el-option>
            <el-option label="选择框" value="radio"></el-option>
          </el-select>
        </el-form-item>

        <!-- 选择框选项管理 -->
        <el-form-item label="选项列表" v-if="fieldForm.fieldType === 'radio'" prop="options">
          <div v-for="(option, index) in fieldForm.options" :key="index" class="option-item">
            <el-input 
              v-model="option.label" 
              placeholder="选项名称"
              class="option-input"
            ></el-input>
            <el-button type="danger" icon="el-icon-delete" circle @click="removeOption(index)"></el-button>
          </div>
          <el-button type="primary" icon="el-icon-plus" @click="addOption">添加选项</el-button>
        </el-form-item>
        <el-form-item label="是否必填" prop="required">
          <el-switch v-model="fieldForm.required"></el-switch>
        </el-form-item>
        <el-form-item label="排序号" prop="sortOrder">
          <el-input-number v-model="fieldForm.sortOrder" :min="1"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitField">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        name: "",
        description: "",
        applicantGroupId: "", // 改为单个值而不是数组
      },
      currentOperation: 'application', // 用于标识当前操作的是申请表字段还是材料清单
      applicantGroupOptions: [
        { id: 1, name: "在职人员" },
        { id: 2, name: "自由职业者" },
        { id: 3, name: "退休人员" },
        { id: 4, name: "在校学生" },
        { id: 5, name: "学龄前儿童" }
      ],
      rules: {
        name: [
          {
            required: true,
            message: "请输入模板名称",
            trigger: "blur",
          },
        ],
        description: [
          {
            required: true,
            message: "请输入模板描述",
            trigger: "blur",
          },
        ],
      },
      materialCategoryData: [],
      applicationFieldData: [], // 申请表字段数据
      dialogVisible: false,
      fieldForm: {
        category: '',
        fieldName: '',
        fieldLabel: '',
        fieldType: '',
        required: false,
        sortOrder: 1,
        options: [] // 新增选项数组
      },
      fieldRules: {
        category: [{ required: true, message: '请输入材料类目', trigger: 'blur' }],
        fieldName: [{ required: true, message: '请输入字段名称', trigger: 'blur' }],
        fieldLabel: [{ required: true, message: '请输入字段标签', trigger: 'blur' }],
        fieldType: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
        sortOrder: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
        options: [{ 
          required: true, 
          message: '选择框类型必须添加选项', 
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (this.fieldForm.fieldType === 'radio' && (!value || value.length === 0)) {
              callback(new Error('请至少添加一个选项'));
            } else {
              callback();
            }
          }
        }]
      }
    };
  },
  methods: {
    addOption() {
      if (!this.fieldForm.options) {
        this.fieldForm.options = [];
      }
      this.fieldForm.options.push({ label: '', value: '' });
    },

    removeOption(index) {
      this.fieldForm.options.splice(index, 1);
    },
    handleFieldTypeChange(value) {
      if (value === 'radio') {
        // 初始化选项数组
        if (!this.fieldForm.options || this.fieldForm.options.length === 0) {
          this.fieldForm.options = [{ label: '', value: '' }];
        }
      } else {
        this.fieldForm.options = [];
      }
    },

    addApplicationField() {
      this.currentOperation = 'application';
      this.$refs.fieldForm && this.$refs.fieldForm.resetFields();
      this.fieldForm = {
        category: '',
        fieldName: '',
        fieldLabel: '',
        fieldType: '',
        required: false,
        sortOrder: 1,
        options: []
      };
      const maxSortOrder = this.applicationFieldData.length > 0
        ? Math.max(...this.applicationFieldData.map(item => item.sortOrder))
        : 0;
      this.fieldForm.sortOrder = maxSortOrder + 1;
      this.dialogVisible = true;
    },
    
    addField() {
      this.currentOperation = 'material';
      const maxSortOrder = this.materialCategoryData.length > 0
        ? Math.max(...this.materialCategoryData.map(item => item.sortOrder))
        : 0;
      this.fieldForm.sortOrder = maxSortOrder + 1;
      this.dialogVisible = true;
    },

    handleEditMaterial(row) {
      // 将当前行数据复制到表单中
      this.fieldForm = { ...row };
      this.dialogVisible = true;
    },
    
    handleDeleteMaterial(row) {
      this.$confirm('确认删除该字段吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 找到要删除的项的索引
        const index = this.materialCategoryData.findIndex(item => 
          item.fieldName === row.fieldName && 
          item.category === row.category
        );
        // 从数组中删除
        if (index !== -1) {
          this.materialCategoryData.splice(index, 1);
          this.$message.success('删除成功');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 修改提交方法，增加对材料清单的处理
    submitField() {
      this.$refs.fieldForm.validate((valid) => {
        if (valid) {
          if (this.fieldForm.fieldType === 'radio') {
            this.fieldForm.options.forEach((option, index) => {
              option.value = option.value || `option${index + 1}`;
            });
          }
          
          // 检查是否是编辑模式（通过查找相同字段名和类目的项）
          const applicationIndex = this.applicationFieldData.findIndex(item => 
            item.fieldName === this.fieldForm.fieldName && 
            item.category === this.fieldForm.category
          );
          
          const materialIndex = this.materialCategoryData.findIndex(item => 
            item.fieldName === this.fieldForm.fieldName && 
            item.category === this.fieldForm.category
          );
          
          if (applicationIndex !== -1) {
            // 更新申请表字段
            this.applicationFieldData.splice(applicationIndex, 1, { ...this.fieldForm });
            this.$message.success('修改成功');
          } else if (materialIndex !== -1) {
            // 更新材料清单字段
            this.materialCategoryData.splice(materialIndex, 1, { ...this.fieldForm });
            this.$message.success('修改成功');
          } else {
            // 根据当前操作的按钮决定添加到哪个数组
            if (this.currentOperation === 'application') {
              this.applicationFieldData.push({ ...this.fieldForm });
            } else {
              this.materialCategoryData.push({ ...this.fieldForm });
            }
            this.$message.success('添加成功');
          }
          
          this.dialogVisible = false;
          this.$refs.fieldForm.resetFields();
        }
      });
    },
    handleConfirm() {
      console.log('确认操作');
    },
    handleCancel() {
      console.log('取消操作');
    },
    handleEditField(row) {
      this.currentOperation = 'application';
      this.fieldForm = { ...row };
      this.dialogVisible = true;
    },
    
    handleDeleteField(row) {
      this.$confirm('确认删除该字段吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.applicationFieldData.findIndex(item => 
          item.fieldName === row.fieldName && 
          item.category === row.category
        );
        if (index !== -1) {
          this.applicationFieldData.splice(index, 1);
          this.$message.success('删除成功');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  }}
</script>

<style scoped>
.basic_info {
  float: left;
}
.clear {
  clear: both;
}
.demo-ruleForm {
  border: 1px solid #dcdfe6;
  padding: 20px;
  border-radius: 15px;
}
.material-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
}
.material_category_table {
  margin-top: 20px;
  text-align: center;
}
.material_category_table .el-button {
  margin: 0 10px;
}
.operation-buttons {
  margin-top: 30px;
  margin-bottom: 30px;
  text-align: center;
}
.operation-buttons .el-button {
  padding: 12px 35px;
  margin: 0 20px;
  font-size: 14px;
}
.option-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.option-input {
  margin-right: 10px;
  width: 200px;
}
</style>

